package com.sell.controller;

import com.lly835.bestpay.model.PayResponse;
import com.sell.dto.OrderDTO;
import com.sell.exceptions.ResultEnum;
import com.sell.exceptions.SellException;
import com.sell.service.OrderService;
import com.sell.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * @Author: megan
 * @Data: 2018/12/10 10:20 PM
 * @Description: 支付模块  sdk ： https://github.com/Pay-Group/best-pay-sdk
 */
@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private PayService payService;

    /**
     * 公众号 h5 支付
     *
     * @param orderId   订单编号
     * @param returnUrl 回调地址
     * @return
     */
    @GetMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId,
                               @RequestParam("returnUrl") String returnUrl,
                               Map<String, Object> map) {
        // 1,查询订单
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (orderDTO == null) {
            throw new SellException(ResultEnum.ORDER_NOT_EXIT);
        }
        // 2,发起支付
        PayResponse response = payService.create(orderDTO);
        map.put("response", response);
        map.put("returnUrl", returnUrl);
        // h5支付 --> 跳转页面进行h5支付
        return new ModelAndView("pay/create", map);
    }

    /**
     * 支付回调（异步通知）
     * 对账，改变订单状态
     *
     * @param notifyData 通知的json串
     */
    @PostMapping("/notify")
    public ModelAndView notify(@RequestBody String notifyData) {
        payService.notify(notifyData);

//      告诉微信处理结果，避免重复通知 (用模板引擎通知微信,这样代码看的更简洁)
        return new ModelAndView("pay/success");
    }
}
